package com.rabbitClient.ttl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Customer {
	public static final String EXCHANGE_NAME = "rabbitClient.dlx.exchange";
	public static final String QUEUE_NAME = "rabbitClient.dlx.queue";
	public static final String ROUTING_KEY = "dlx.save";
	
	public static final String HOST = "192.168.1.219";
	public static final String USER = "guest";
	public static final String PASSWORD = "guest";
	public static final int PORT = 5672;
	public static final String VIRTUAL_HOST = "test";

	public static void main(String[] args) throws IOException, TimeoutException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(HOST);
		factory.setPort(PORT);
		factory.setVirtualHost(VIRTUAL_HOST);
		factory.setUsername(USER);
		factory.setPassword(PASSWORD);

		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		// 每次从队列获取的数量——消费端限流
		channel.basicQos(10);
		
		//死信交换机和队列声明
		channel.exchangeDeclare("dlx.exchange", "topic", true, false, null);
		channel.queueDeclare("dlx.queue", true, false, false, null);
		channel.queueBind("dlx.queue", "dlx.exchange", "dlx");
				
		//声明交换机
		channel.exchangeDeclare(EXCHANGE_NAME, "topic", true, false, null);
		// 声明要关注的队列，因为在生产者中已经声明了，所以这里不需要再声明了
		Map<String , Object> arguments = new HashMap<String, Object>();
		arguments.put("x-dead-letter-exchange", "dlx.exchange");
		channel.queueDeclare(QUEUE_NAME, true, false, false, arguments);
		channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
		
		System.out.println("Customer wait received messages:");
		Consumer consumer = new DefaultConsumer(channel) {
			// 会阻塞，持续等到新的消息进入队列，一旦有新的消息就进行接收并处理消息
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				String message = new String(body, "UTF-8");
				System.out.println(message);
				if ("hello RabbitMQ2".equals(message)) {

					System.out.println("此消息将不处理");
					// 消费者未能消费此消息
					// 第三个参数，将这个消息重新放入到队列中，那么此消费者会持续受到这条消息
					// 如果不返回确认或者不确认的话，则不会有新的信息进入
					channel.basicNack(envelope.getDeliveryTag(), false, true);

				} else {
					// 如果不返回确认或者不确认的话，则不会有新的信息进入
					channel.basicAck(envelope.getDeliveryTag(), false);
				}

			}
		};
		// 自动回复队列应答
		channel.basicConsume("dlx.queue", false, consumer);

	}
}
